package com.upload.controller;

import com.alibaba.fastjson.JSONObject;
import com.upload.bean.myNative.AuditUploadInfoBean;
import com.upload.bean.web.FileUploadRequestBean;
import com.upload.bean.web.FileUploadResponseBean;
import com.upload.bean.yCoin.UploaderInfuRequestBean;
import com.upload.bean.yCoin.YcoinRequestBean;
import com.upload.bean.yCoin.UploaderInfoResponseBean;
import com.upload.bean.yCoin.YcoinResponseBean;
import com.upload.domain.Document;
import com.upload.enums.Status;
import com.upload.jms.audited.AuditToYcoinClient;
import com.upload.jms.audited.UploadToWebClient;
import com.upload.jms.unaudit.GetUploaderInfoClient;
import com.upload.repository.DocumentRepository;
import com.upload.util.CopyFileUtil;
import com.upload.util.FileUtil;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.jms.JMSException;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by STARF on 2017/3/22.
 */
@RestController
public class AuditController {

    @Value("${auditedPath}")
    private String auditedPath;
    @Value("${refuse}")
    private String refuse;

    /**
     * 获取未审核文件的Bean
     * @return  未审核用户信息列表
     */
    @RequestMapping(value = "api/unaudit")
    public List<AuditUploadInfoBean> getUnauditFileList() throws InterruptedException {

        List<AuditUploadInfoBean> auditUploadInfoBeanList = new LinkedList<>();
        Iterator<Document> documentIterator = documentRepository.findByStatus(Status.unaudited).iterator();

        while (documentIterator.hasNext()) {
            Document document = documentIterator.next();
            AuditUploadInfoBean auditUploadInfoBean = new AuditUploadInfoBean();
            auditUploadInfoBean.setFilename(document.getFileName());
            auditUploadInfoBean.setId(document.getId());
            auditUploadInfoBean.setUploadDate(new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss").format(document.getUploadDate()));

            //发送获取头像+昵称的请求，参数unionid
            UploaderInfuRequestBean requestBean = new UploaderInfuRequestBean(document.getUploadUnionid());
            UploaderInfoResponseBean responseBean = null;
            try {
                responseBean = getUploaderInfoClient.sender(requestBean);
                System.out.println("responseBean---"+responseBean.getNickName());
                System.out.println("responseBean---"+responseBean.getHeadImgUrl());
            } catch (JMSException e) {
                e.printStackTrace();
            }
            auditUploadInfoBean.setHeadImgUrl(responseBean.getHeadImgUrl());
            auditUploadInfoBean.setNickName(responseBean.getNickName());

            System.out.println("输出UserInfo=============");
            System.out.println(auditUploadInfoBean.getHeadImgUrl());
            System.out.println(auditUploadInfoBean.getNickName());
            auditUploadInfoBeanList.add(auditUploadInfoBean);
        }
        return auditUploadInfoBeanList;
    }

    /**
     * 文件下载预览
     * @param request
     * @param response
     * @param id    文件id
     * @throws IOException
     */
    @RequestMapping(value = "api/download")
    public void downloadFile(HttpServletRequest request,
                             HttpServletResponse response, @RequestParam("id") long id) throws IOException {
        System.out.println(id);
        Document document = documentRepository.findOne(id);
        String filePath = document.getFilePath();

        File downloadFile = new File(filePath);
        ServletContext context = request.getServletContext();
        String mimeType = context.getMimeType(filePath);
        if (mimeType == null) {
            mimeType =  "application/octet-stream";
            System.out.println("context getMimeType is null");
        }
        System.out.println("MIME type: " + mimeType);

        response.setContentType(mimeType);
        response.setContentLength((int) downloadFile.length());

        // 设置响应头
        String headerKey = "Content-Disposition";
//        String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
        String headerValue = String.format("inline; filename=", downloadFile.getName());
//        String headerValue = downloadFile.getName();
        response.setHeader(headerKey, headerValue);

        // 将流复制到响应的输出流中
        try {
            InputStream myStream = new FileInputStream(filePath);
            IOUtils.copy(myStream, response.getOutputStream());
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("下载成功");
    }

    /**
     * 审核结果
     * @param value  审核结果json
     * @return
     * @throws IOException
     */
    @PostMapping(value = "api/audit")
    @ResponseBody
    public boolean auditResult(@RequestBody String value) throws IOException, InterruptedException {
        JSONObject jsonObject = (JSONObject) JSONObject.parse(value);
        long id = jsonObject.getLong("id");
        long yCoin = jsonObject.getLong("ycoin");
        String checkUnionid = jsonObject.getString("unionid");

        System.out.println("111111111111111");

        if (checkUnionid == null){
            System.out.println("审核人为null");
            return false;
        }
        Document document = documentRepository.findOne(id);
        String fileName = document.getFileName();
        String filePath = document.getFilePath();

        //将审核结果写到记录中
        document.setCheckDate(new Date());
        document.setCheckUnionid(checkUnionid);
        if (yCoin>0) {
            System.out.println("yCoin>0------");
            document.setClassify("/环球数据/免费资料/专业课真题/");

            String[] classfy = {document.getClassify()};

            //拷贝通过审核的文件
            System.out.println(filePath+"------------filePath");
            String destFile = auditedPath+fileName;
            System.out.println(destFile+"-------------destFile");
            CopyFileUtil copyFileUtil = new CopyFileUtil();
            copyFileUtil.copyFile(filePath, destFile);

            //删除原文件
            FileUtil fileUtil = new FileUtil();
            fileUtil.deleteFile(filePath);
            System.out.println("删除文件");

            //向网站发送消息
            FileUploadRequestBean fileUploadRequestBean = new FileUploadRequestBean(id);
            FileUploadResponseBean fileUploadResponseBean = null;
            fileUploadRequestBean.setFileName(fileName);
            fileUploadRequestBean.setClassfy(classfy);
            fileUploadRequestBean.setCollege(document.getCollege());
            fileUploadRequestBean.setFilePath(filePath);
            fileUploadRequestBean.setSubjectCode(document.getSubjectCode());
            fileUploadRequestBean.setTime(document.getTime());
            try {
                //TODO  网站返回信息的处理
                fileUploadResponseBean = uploadToWebClient.sender(fileUploadRequestBean);

                System.out.println(fileUploadResponseBean);
            } catch (JMSException e) {
                e.printStackTrace();
            }

            //通知逸贝系统加逸贝
            YcoinRequestBean ycoinRequestBean = new YcoinRequestBean(document.getUploadUnionid());
            ycoinRequestBean.setCheckUnionid(checkUnionid);
            ycoinRequestBean.setCheckDate(new Date().getTime());
            ycoinRequestBean.setyCoin(yCoin);
            YcoinResponseBean ycoinResponseBean = null;
            try {
                ycoinResponseBean = auditToYcoinClient.sender(ycoinRequestBean);
                System.out.println("ycoinResponseBean---------------"+ycoinResponseBean.toString());
            } catch (JMSException e) {
                e.printStackTrace();
            }
            if (ycoinResponseBean.isSuccess()) {
                document.setyCoin(yCoin);
                document.setStatus(Status.audited);
                documentRepository.save(document);

                return true;
            } else {
                System.out.println("逸贝系统审核失败！！！！");
                document.setStatus(Status.refuse);
                documentRepository.save(document);
                return false;
            }
        } else {
            System.out.println("审核不合格！！！！");
            document.setStatus(Status.refuse);
            documentRepository.save(document);

            //备份不通过审核的文件
            String destFilePath = refuse+fileName;
            CopyFileUtil copyFileUtil = new CopyFileUtil();
            copyFileUtil.copyFile(filePath,destFilePath);

            //删除原文件
            FileUtil fileUtil = new FileUtil();
            fileUtil.deleteFile(filePath);

            return false;
        }
    }

    @Autowired
    private DocumentRepository documentRepository;

    @Autowired
    private GetUploaderInfoClient getUploaderInfoClient;

    @Autowired
    private UploadToWebClient uploadToWebClient;

    @Autowired
    private AuditToYcoinClient auditToYcoinClient;

}
